<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片压缩工具</title>
    <link rel="stylesheet" href="../../bootstrap/bootstrap.min.css">
</head>

<body>
    <div class="container mt-5">
        <h1 class="mb-4">图片压缩工具</h1>
        <form class="mb-3">
            <div class="md-3">
                <input class="form-control" type="file" id="imageInput" accept=".jpeg,.jpg,.png">
            </div>
            <div class="form-floating mt-3">
                <input type="number" class="form-control" placeholder="请输入要压缩的质量（1-100）" id="qualityInput">
                <label for="qualityInput">请输入要压缩的质量（1-100）</label>
            </div>
        </form>
        <button type="button" class="btn btn-primary" onclick="compressImage()">压缩</button>
        <div class="mt-4">
            <p>原始图片大小：<span id="originalSize">0</span></p>
            <p>压缩后图片大小：<span id="compressedSize">0</span></p>
            <p>压缩率：<span id="compressionRate">0%</span></p>
        </div>
    </div>
    <script>
        function compressImage() {
            // 获取选择的图片文件
            const fileInput = document.getElementById("imageInput");
            const files = fileInput.files;
            if (!files || files.length === 0) {
                alert("请选择要压缩的图片！");
                return;
            }
            const file = files[0];

            // 获取压缩质量
            const qualityInput = document.getElementById("qualityInput");
            let quality = parseInt(qualityInput.value);
            if (isNaN(quality)) {
                quality = 80; // 默认为80
            } else if (quality < 1) {
                quality = 1;
            } else if (quality > 100) {
                quality = 100;
            }

            // 创建一个图片对象
            const image = new Image();
            image.onload = function () {
                // 创建一个canvas对象来进行压缩
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");

                // 设置canvas的宽高和绘制区域
                const width = image.width;
                const height = image.height;
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(image, 0, 0, width, height);

                // 输出格式判断
                const mimeType = file.type;
                let format = "image/jpeg"; // 默认使用JPEG格式
                let extension = ".jpg";
                if (mimeType === "image/png") {
                    format = "image/png";
                    extension = ".png";
                    quality *= 2; // 提高quality / 100的值
                }

                // 将canvas转换为Blob对象
                canvas.toBlob(function (blob) {
                    const compressedSize = blob.size;
                    const originalSize = file.size;
                    const compressionRate = Math.round((1 - compressedSize / originalSize) * 100);

                    // 更新页面显示的统计结果
                    document.getElementById("originalSize").innerHTML = `${(originalSize / 1024).toFixed(2)}KB`;
                    document.getElementById("compressedSize").innerHTML = `${(compressedSize / 1024).toFixed(2)}KB`;
                    document.getElementById("compressionRate").innerHTML = `${compressionRate}%`;

                    // 创建一个a标签并设置下载属性，然后模拟点击下载
                    const url = URL.createObjectURL(blob);
                    const link = document.createElement("a");
                    link.href = url;
                    link.download = "compressed" + extension;
                    link.click();
                }, format, quality / 100); // 将canvas转换为原格式并设置压缩质量
            };
            image.src = URL.createObjectURL(file);
        }
    </script>

</body>

</html>